package com.yc.endpointer;

import com.yc.exception.CustomException;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2023/12/27 15:37
 */
@Component
@ServerEndpoint("/wx/clock/{key}")
public class ClockEndpoint {

    // 用来存储每一个考勤对象对应的ClockEndpoint对象
    public static Map<String, ClockEndpoint> onlineClocking = new ConcurrentHashMap<>();

    private Session session;

    // 连接服务器时调用
    @OnOpen
    public void onOpen(@PathParam("key") String key, Session session, EndpointConfig config) {
        System.out.println("websocket连接成功");
        this.session = session;
        onlineClocking.put(key, this);
        try {
            sendMessage(session,"Hello World");
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("0", "系统异常");
        }
    }

    // 发送消息时调用
    @OnMessage
    public void onMessage(@PathParam("key") String key, String msg) {
        try {
            // 根据uuid获取当前的二维码
            ClockEndpoint clockEndpoint = onlineClocking.get(key);
            // 推送消息给前台
            sendMessage(clockEndpoint.session, msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 连接关闭时调用
    @OnClose
    public void onClose(Session session) {

    }

    /**
     * 实现服务器主动推送
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(Session session, String message) throws IOException {
        session.getAsyncRemote().sendText(message);
    }
    
}
